
import 'package:flutter_libserialport/flutter_libserialport.dart';

import '../log/logger.dart';
import '../main.dart';
import 'result_handler.dart';



class HfSerialPortHelper{

  static final Map<String, HfSerialPortHelper> _cache = <String, HfSerialPortHelper>{};
  final String url;
  final int baudRate;

  factory HfSerialPortHelper(String url,int baudRate) {
    return _cache.putIfAbsent(url, () => HfSerialPortHelper._internal(url,baudRate));
  }

  HfSerialPortHelper._internal(this.url,this.baudRate){
    open(url,baudRate);
  }

  ResultHandler analysisHelper = ResultHandler();
  SerialPort? port;
  SerialPortReader? reader;

  open(name,baudRate){
    port?.close();
    port = null;
    port = SerialPort(name);
    if(port!.isOpen) {
      print('port hasOpened');
    }
    if(!port!.openReadWrite()){
      print('openReadWrite ${SerialPort.lastError}');
      // port!.close();
      return;
    }
    print('$name is open');
    port!.config = SerialPortConfig()
      ..baudRate = baudRate
      ..bits = 8
      ..stopBits = 1
      ..parity = SerialPortParity.none
      ..setFlowControl(SerialPortFlowControl.none);
    setReader();
  }

  close(){
    reader?.close();
    reader = null;
    port?.close();
    port = null;
    _cache.remove(url);
  }

  setReader(){
    reader?.close();
    reader = null;
    reader = SerialPortReader(port!);
    reader!.stream.listen((data) {
      String hexString = data.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
      print("received=$hexString");
      if(settingEntity.log??false){
        Logger().write('received = $hexString\r\n');
      }
      analysisHelper.dataReceived(hexString.toUpperCase());
    },onError: (e){
      if(reader!=null){
        reader!.close();
      }
      print('onError${e.toString()}');
    },onDone: (){
      close();
      print("onDone");
    });

  }

  sendData(data){
    clear();
    port!.write(data);
  }

  clear(){
    analysisHelper.clear();
  }
}